<template>
  <el-select v-model="selectedValue" collapse-tags :clearable="clearable" :filterable="filterable" :placeholder="$t('placeholder.choose')" @change="handleChange" :disabled="disabled">
    <el-option v-for="item in items" :key="item.value" :label="getLabel ? item.label : item.value" :value="item.value"></el-option>
  </el-select>
</template>

<script>
  export default {
    name: 'dictValueSelect',
    props: {
      code: '',
      codeDefault: '',
      filterable: false,
      allList: false,
      disabled: false,
      getLabel: {
        type: Boolean,
        default: true
      },
      value: '',
      clearable: true
    },
    data() {
      return {
        selectedValue: null,
        items: [],
        map: new Map()
      };
    },
    methods: {
      handleChange(val) {
        const item = this.map[val];
        this.$emit('change', val, item);
      },
      getItems() {
        if (this.code) {
          // console.log(this.code)
          const list = this.$store.getters.allDic[this.code];

          list.forEach(res => {
            const val = this.getLabel ? res.value : res.label;
            if (this.codeDefault === val) {
              this.selectedValue = val;
            }
          });
          if (this.allList) {
            const obj = [{ id: 'all', label: this.$t('components.dictValueSelect.all'), value: '' }];
            const param = obj.concat(this.$store.getters.allDic[this.code]);
            this.items = param;
          } else {
            this.items = this.$store.getters.allDic[this.code];
          }
          this.map = this.$store.getters.allMapDic[this.code];
        }
      }
    },
    watch: {
      value(val) {
        this.selectedValue = val;
      },
      selectedValue(val) {
        this.$emit('input', val);
      },
      code(val) {
        this.getItems();
        this.$emit('change', val, this.item);
      },
      codeDefault(val) {
        this.getItems();
        this.$emit('change', val, this.item);
      }
    },
    mounted() {
      this.items = [];
      this.selectedValue = this.value;
      this.getItems();
    }
  };
</script>

<style scoped>
</style>
